package ph.com.gs3.formalistics.presenter.adapters;

import java.util.ArrayList;
import java.util.List;

import ph.com.gs3.formalistics.R;
import ph.com.gs3.formalistics.model.valueobjects.business.User;
import ph.com.gs3.formalistics.service.managers.ImageManager;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class UserListItemViewAdapter extends BaseAdapter {

	public static final String TAG = UserListItemViewAdapter.class.getSimpleName();

	private Context context;
	private List<User> users;
	private ImageManager imageManager;

	public UserListItemViewAdapter(Context context, List<User> onlineUsers) {

		this.context = context;
		this.users = onlineUsers == null ? new ArrayList<User>() : onlineUsers;

		imageManager = ImageManager.getDefaultInstance(context.getApplicationContext());

	}

	@Override
	public int getCount() {
		return users.size();
	}

	@Override
	public Object getItem(int index) {
		return users.get(index);
	}

	@Override
	public long getItemId(int index) {
		return users.get(index).getId();
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {

		View row = convertView;
		UserListItemHolder holder = null;

		User user = (User) getItem(position);

		if (row == null) {
			LayoutInflater inflater = (LayoutInflater) context
			        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

			row = inflater.inflate(R.layout.view_online_user, parent, false);
			holder = new UserListItemHolder(row);
			row.setTag(holder);

		}

		holder = (UserListItemHolder) row.getTag();
		holder.tvDisplayName.setText(user.getDisplayName());
		imageManager.requestUserImage(Integer.toString(user.getWebId()), user.getAccountServer(),
		        holder.ivAvatar);

		return row;
	}

	public void resetItems(List<User> users) {
		this.users.clear();
		this.users.addAll(users);
		notifyDataSetChanged();
	}
	
	public static class UserListItemHolder {

		ImageView ivAvatar;
		TextView tvDisplayName;

		public UserListItemHolder(View rootView) {

			ivAvatar = (ImageView) rootView.findViewById(R.id.OnlineUser_ivAvatar);
			tvDisplayName = (TextView) rootView.findViewById(R.id.OnlineUser_tvDisplayName);

		}

	}

}
